package com.baiduspring.web.valicode;

import com.baiduspring.utils.valicode.Captcha;
import com.baiduspring.utils.valicode.GifCaptcha;
import com.baiduspring.utils.valicode.SpecCaptcha;
import com.baiduspring.vo.ValidateVO;
import org.springframework.context.annotation.Scope;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@Scope("prototype")
public class ValiCodeController {
    /**
     * 获取验证码（Gif版本）
     *
     * @param response
     */
    @GetMapping(value = "/valicode/gif")
    public void getGifCode(HttpServletResponse response, HttpServletRequest request) {
        try {
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/gif");
            /**
             * gif格式动画验证码
             * 宽，高，位数。
             */
            Captcha captcha = new GifCaptcha(146, 33, 4);
            //输出
            captcha.out(response.getOutputStream());
            HttpSession session = request.getSession(true);
            //存入Session
            session.setAttribute("_code", captcha.text().toLowerCase());
        } catch (Exception e) {

        }
    }


    /**
     * 获取验证码（jpg版本）
     *
     * @param response
     */
    @GetMapping(value = "/valicode/jpg")
    public void getJPGCode(HttpServletResponse response, HttpServletRequest request) {
        try {
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/jpg");
            /**
             * jgp格式验证码
             * 宽，高，位数。
             */
            Captcha captcha = new SpecCaptcha(146, 33, 4);
            //输出
            captcha.out(response.getOutputStream());
            HttpSession session = request.getSession(true);
            //存入Session
            session.setAttribute("_code", captcha.text().toLowerCase());
        } catch (Exception e) {
        }
    }

    /**
     * 验证验证码是否输入正确
     *
     * @param request http request对象
     * @param code    验证码
     * @return 返回布尔值，true表示成功，false表示失败
     */
    @GetMapping("/valicode/isright")
    public ValidateVO<String> validateCode(HttpServletRequest request, String code) {
        if (StringUtils.isEmpty(code)) {
            return new ValidateVO<>(false, "验证码不能为空");
        }

        String $code = request.getSession().getAttribute("_code").toString();
        if (code.equalsIgnoreCase($code)) {
            return new ValidateVO<>(true);
        }
        return new ValidateVO<>(false, "验证码不正确");
    }
}
